package com.feeyo.nfc;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

/**
 * 1.本Activity接收到nfc intent时，取出id
 * 2.携带id发送广播
 * <p>
 * 怎么接收：
 * 1.创建BroadcastReceiver，manifest中<action android:name="com.feeyo.acdm.intent.nfc.discovered"/>
 * 2.onReceive()中的intent中包含id，key为NfcConstants.KEY_NFC_ID，后续自由处理。
 * 后续打开的Activity注意保持单例，onCreate()和onNewIntent()都可能被执行，都要处理。
 * Created by zzw on 2017/3/2.
 */

public class NfcActivity extends Activity {
    private NfcUtil mNfcUtil;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mNfcUtil = new NfcUtil(this);
        resolveIntent(getIntent());
    }

    @Override
    protected void onPause() {
        super.onPause();
        mNfcUtil.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mNfcUtil.onResume();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        resolveIntent(intent);
    }

    private void resolveIntent(Intent intent) {
        long nfcId = mNfcUtil.getNfcId(intent);
        if (nfcId != 0) {
            Intent sendIntent = new Intent();
            sendIntent.setAction(NfcConstants.NFC_BROADCAST_ACTION);
            sendIntent.putExtra(NfcConstants.KEY_NFC_ID, nfcId);
            sendBroadcast(sendIntent);
        }
        Log.d("nfc", "id is " + nfcId);
        finish();
    }
}
